package cn.hbwe.service.impl;

import cn.hbwe.Dto.dLoginDTO;
import cn.hbwe.Dto.dRegisterDTO;
import cn.hbwe.mapper.DepartmentMapper;
import cn.hbwe.pojo.dto.DoctorDto;
import cn.hbwe.pojo.entity.Department;
import cn.hbwe.pojo.entity.Doctor;
import cn.hbwe.mapper.DoctorMapper;
import cn.hbwe.pojo.vo.DoctorVo;
import cn.hbwe.service.IDepartmentService;
import cn.hbwe.service.IDoctorService;
import cn.hbwe.util.CustomException;
import cn.hbwe.util.PageVO;
import cn.hbwe.util.constant.MessageConstant;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 7组
 * @since 2023-10-18
 */
@Service
@Slf4j
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements IDoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private IDepartmentService departmentService;
    /**
     * 根据科室id查询医生信息
     * @param id
     * @return
     */
    /*@Override
    public List<Doctor> getByDepartmentId(Integer id) {
        return doctorMapper.getByDepartmentId(id);
    }*/
    @Override
    public PageVO<DoctorVo> getByDepartmentId(Long currentPage, Long pageSize, Integer id) {

        Page<Doctor> page = Page.of(currentPage, pageSize);
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, Doctor::getDepartmentId, id).eq(Doctor::getDoctorStatus,0).orderByAsc(Doctor::getDoctorNo);
        Page<Doctor> doctorPage = page(page, lqw);

        long total = doctorPage.getTotal();
        long current = doctorPage.getCurrent();
        List<Doctor> doctors = doctorPage.getRecords();
        if (doctors == null) {
            return PageVO.of(total, current, Collections.emptyList());
        }

        List<DoctorVo> doctorVos = BeanUtil.copyToList(doctors, DoctorVo.class);
        for (Doctor doctor : doctors) {
            Integer departmentId = doctor.getDepartmentId();
            Department department = departmentMapper.selectById(departmentId);

            for (DoctorVo doctorVo : doctorVos) {
                if (departmentId == doctorVo.getDepartmentId()){
                    doctorVo.setDepartmentName(department.getDepartmentName());
                }
            }
        }

        return PageVO.of(total, current,doctorVos);
    }

    /**
     * 医生分页查询
     * @param currentPage
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public PageVO<DoctorVo> getDoctorVo(Long currentPage, Long pageSize, String name) {
        Page<Doctor> page = Page.of(currentPage, pageSize);
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null,Doctor::getDoctorName, name);
        Page<Doctor> doctorPage = page(page, lqw);

        long total = doctorPage.getTotal();
        long current = doctorPage.getCurrent();
        List<Doctor> doctors = doctorPage.getRecords();
        if (doctors == null) {
            return PageVO.of(total, current, Collections.emptyList());
        }

        List<DoctorVo> doctorVos = BeanUtil.copyToList(doctors, DoctorVo.class);

        for (Doctor doctor : doctors) {
            Integer departmentId = doctor.getDepartmentId();
            Department department = departmentMapper.selectById(departmentId);

            for (DoctorVo doctorVo : doctorVos) {
                if (departmentId == doctorVo.getDepartmentId()){
                    doctorVo.setDepartmentName(department.getDepartmentName());
                }
            }
        }

        return PageVO.of(total, current,doctorVos);
    }

    /**
     * 修改医生信息
     * @param doctorDto
     * @return
     */
    @Transactional
    @Override
    public void updateDoctor(DoctorDto doctorDto) {

        String departmentName = doctorDto.getDepartmentName();
        LambdaQueryWrapper<Department> lqw = new LambdaQueryWrapper<>();
        lqw.eq(departmentName != null, Department::getDepartmentName, departmentName);
        Department department = departmentMapper.selectOne(lqw);
        doctorDto.setDepartmentId(department.getDepartmentId());
        this.updateById(doctorDto);
    }

    /**
     * 添加医生信息
     * @param doctorDto
     * @return
     */
    @Override
    @Transactional
    public void saveDoctor(DoctorDto doctorDto) {
        String departmentName = doctorDto.getDepartmentName();
        LambdaQueryWrapper<Department> lqw = new LambdaQueryWrapper<>();
        lqw.eq(departmentName != null, Department::getDepartmentName, departmentName);

        String password = doctorDto.getDoctorPassword();
       doctorDto.setDoctorPassword(DigestUtils.md5DigestAsHex(password.getBytes()));


        Department department = departmentMapper.selectOne(lqw);
        doctorDto.setDepartmentId(department.getDepartmentId());
        this.save(doctorDto);
    }






    /**
     * 用户登录
     * @param dloginDTO
     * @return
     */
    @Override
    public Doctor dlogin(dLoginDTO dloginDTO) {
        //条件构造器
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Doctor::getDoctorNo, dloginDTO.getDoctorNo());
        lqw.orderByDesc(Doctor::getDoctorId);

        //查询
        Doctor doctor = this.getOne(lqw);

        //是否查询到此用户
        if (doctor == null) {

            throw new CustomException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //md5密码加密
        String password = dloginDTO.getDoctorPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //密码是否正确
        if (!doctor.getDoctorPassword().equals(password)) {
            throw new CustomException(MessageConstant.PASSWORD_ERROR);
        }

        //返回结果
        return doctor;
    }

    /**
     * 用户注册
     * @param dregisterDTO
     * @return
     */
    @Override
    public Doctor dregister(dRegisterDTO dregisterDTO) {
        //条件构造器
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Doctor::getDoctorNo,dregisterDTO.getDoctorNo());

        //查询,判断新的用户名是否存在
        long count = count(lqw);
        if (count > 0) {
            throw new CustomException(MessageConstant.ALREADY_EXISTS);
        }




        //查询科室是否存在
        LambdaQueryWrapper<Department> cs = new LambdaQueryWrapper<>();
        cs.eq(Department::getDepartmentId,dregisterDTO.getDepartmentID());
        long find = departmentService.count(cs);
        if (find == 0) {
            throw new CustomException(MessageConstant.CATEGORY_NOT_EXISTS );
        }


        //md5加密
        String password = dregisterDTO.getDoctorPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Doctor doctor =Doctor.builder()
                .doctorName(dregisterDTO.getDoctorName())
                .doctorPassword(password)
                .doctorNo(dregisterDTO.getDoctorNo())
                .doctorEmail(dregisterDTO.getDoctorEmail())
                .doctorSex(dregisterDTO.getDoctorSex())
                .doctorSpecialty(dregisterDTO.getDoctorSpeciality())
                .departmentId(dregisterDTO.getDepartmentID())
                .price(dregisterDTO.getPrice())
                .build();

        //添加
        this.save(doctor);

        //返回
        return doctor;
    }


    @Override
    @Transactional
    public List<Doctor> getByDoctorName(String doctorName) {
        LambdaQueryWrapper<Doctor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Doctor::getDoctorName,doctorName);
        return doctorMapper.selectList(lqw);
    }

    //--------yuhangyu---------------
    public Doctor selectByOneself(int doctorId){
        Doctor doctor=doctorMapper.selectById(doctorId);
        return doctor;
    }


    public String dname(int id){
        Doctor doctor = doctorMapper.selectById(id);
        String dname= doctor.getDoctorName();

        return dname;
    }


}
